package com.baocaiqiche.dev.taoforandroid;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.util.jar.Manifest;

public class MultiMediaActivity extends AppCompatActivity implements View.OnClickListener{

    private static final int TAKE_PHOTO = 1 ;
    private static final int CHOOSE_PHOTO = 2 ;
    private Button imageBtn , albumBtn ,redioBtn , videoBtn ;
    private ImageView picture;
    private Uri imageUri ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_media);
        imageBtn = (Button) findViewById(R.id.imageBtn);
        redioBtn = (Button) findViewById(R.id.redioBtn);
        videoBtn = (Button) findViewById(R.id.videoBtn);
        albumBtn = (Button) findViewById(R.id.albumBtn);

        imageBtn.setOnClickListener(this);
        albumBtn.setOnClickListener(this);
        redioBtn.setOnClickListener(this);
        videoBtn.setOnClickListener(this);

        picture = (ImageView) findViewById(R.id.imageView);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.imageBtn:
                File outputImage = new File(getExternalCacheDir(),"output_image.jpg");
                try {
                    if (outputImage.exists()) {
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                }catch(IOException e){
                    e.printStackTrace();
                }

                if(Build.VERSION.SDK_INT >= 24){
                    imageUri = FileProvider.getUriForFile(MultiMediaActivity.this,"com.baocaiqiche.dev.taoforandroid.fileprovider",outputImage);
                }else{
                    imageUri = Uri.fromFile(outputImage);
                }

                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                startActivityForResult(intent,TAKE_PHOTO);
                break;
            case R.id.albumBtn:
                if(ContextCompat.checkSelfPermission(MultiMediaActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(MultiMediaActivity.
                            this,new String [] {android.Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }else{
                    openAlbum();
                }
                break;
            case R.id.redioBtn:
                break;
            case R.id.videoBtn:
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode , int resultCode , Intent data){

        switch (requestCode){

            case TAKE_PHOTO:

                if(resultCode == RESULT_OK){
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }

                break;

            case CHOOSE_PHOTO:

                if(resultCode == RESULT_OK){

                    if(Build.VERSION.SDK_INT >= 19){
                        //4.4以上
                        handleImageOnKitKat(data);
                    }else{
                        //4.4以下
                        handleImageBeforeKitKat(data);
                    }

                }

                break;

            default:

                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode , @NonNull String [] permissions , @NonNull int[] grantResults){
        switch (requestCode){
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                }else{
                    Toast.makeText(MultiMediaActivity.this,"您取消了授权",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void openAlbum(){
        Intent albumIntent = new Intent("android.intent.action.GET_CONTENT");
        albumIntent.setType("image/*");
        startActivityForResult(albumIntent,CHOOSE_PHOTO);
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {

        String imagePath = null;
        Uri uri = data.getData();

        if(DocumentsContract.isDocumentUri(this,uri)){
            //如果是document类型的Uri 则通过document id 处理
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                imagePath = getImagePath(contentUri,null);
            }

        }else if("content".equalsIgnoreCase(uri.getScheme())){

            //如果是content类型的Uri 则是用普通的处理方式
            imagePath = getImagePath(uri,null);

        }else if("file".equalsIgnoreCase(uri.getScheme())){

            //如果是file类型的Uri 直接获取图片路径即可
            imagePath = uri.getPath();

        }

        displayImage(imagePath);
    }

    private void handleImageBeforeKitKat(Intent data){
        Uri uri = data.getData();
        String imagePath = getImagePath(uri,null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri , String selection){

        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if(cursor != null){
            if(cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }

        return path ;

    }

    private void displayImage(String imagePath){
        if(imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitmap);
        }else{
            Toast.makeText(MultiMediaActivity.this,"获取图片失败",Toast.LENGTH_SHORT).show();
        }
    }
}
